import {databus} from '../databus'
/**
 * 游戏基础的精灵类
 */

export default class Sprite {
  constructor(imgSrc = '', width = 0, height = 0, x = 0, y = 0,twidth = 0, theight = 0, tx = 0, ty = 0,spriteName = '') {
    this.img = new Image()
    this.img.src = imgSrc
    
    this.width = width
    this.height = height

    this.x = x
    this.y = y

    this.twidth = twidth
    this.theight = theight
    this.tx = tx
    this.ty = ty
    this.spriteName = spriteName
    this.dir = imgSrc.substring(0, imgSrc.lastIndexOf('/'))+'/';
    this.visible = true
    this.frameIndex = 0;
    this.frameLoop = 0;
    this.posx = this.tx+8
    this.posy = this.ty+4
    
    if(spriteName!=''){
      this.readResource()
    }
   
  }
  readResource(){
    
    // 先判断文件是否存在
    try {
      let resatk, resconfig, resmagic, resnormal;
      try {
          resatk = wx.getFileSystemManager().readFileSync(this.dir + 'atk.txt', 'utf-8');
          this.atk = this.parseTxt(resatk,'atk');
      } catch (error) {
        this.atk = {};
      }
      try {
          resconfig = wx.getFileSystemManager().readFileSync(this.dir + 'config.txt', 'utf-8');
          this.config = this.parseTxt(resconfig,'config');
      } catch (error) {
        this.config = {};
      }
      try {
          resmagic = wx.getFileSystemManager().readFileSync(this.dir + 'magic.txt', 'utf-8');
          this.magic = this.parseTxt(resmagic,'magic');
      } catch (error) {
        this.magic = {};
      }
      try {
          resnormal = wx.getFileSystemManager().readFileSync(this.dir + 'normal.txt', 'utf-8');
          this.normal = this.parseTxt(resnormal,'normal');
      } catch (error) {
        this.normal = {};
      }
    //  console.log(this.spriteName,this.img.width,this.img.height,this.twidth,this.theight)
      
    } catch (error) {
      console.log('文件读取失败:' + error);
    }
  }
  parseTxt(txt,type) {
    let result = {};
    if(type=='config'){
      const lines = txt.split('\n');
      lines.forEach(line => {
          const parts = line.split('=');
          if (parts.length === 2) {
              const key = parts[0].trim();
              const value = parts.slice(1).join('=').trim().replace(/"/g, '');
              result[key] = value;
          }
      });
    }else{
      const lines = txt.split('\n').filter(line => line.trim() !== '');
      result = lines.map(line => {
        const [frame, duration] = line.split(',');
        return { frame: frame.trim().replace(/"/g, ''), duration: parseFloat(duration) };
      });
    }
    return result;
  }
  
  

  /**
   * 将精灵图绘制在canvas上
   */
  drawToCanvas(ctx) {
    if (!this.visible) return
    this.twidth = this.twidth==0?this.img.width:this.twidth
    this.theight = this.theight==0?this.img.height:this.theight
    if(this.spriteName == 'liu_qing_feng' ){
      ctx.drawImage(
        this.img,
        this.x+1, // 源图像的x坐标
        this.y+1, // 源图像的y坐标
        15, // 源图像的宽度
        30, // 源图像的高度
        8*16*devicePixelRatio, // 目标画布上源图像左上角的 x 坐标
        3*16*devicePixelRatio, // 目标画布上源图像左上角的 y 坐标
        16*devicePixelRatio, // 画布上绘制图像的宽度
        32*devicePixelRatio // 画布上绘制图像的高度
      )
      // console.log('lqf',16*devicePixelRatio,32*devicePixelRatio)
    }else if(this.spriteName =='' ||this.spriteName =='startMovie' ||this.spriteName =='arrow'||this.spriteName =='sayHead'){
      ctx.drawImage(
        this.img,
        this.x * devicePixelRatio, // 源图像的x坐标
        this.y * devicePixelRatio, // 源图像的y坐标
        this.img.width * devicePixelRatio, // 源图像的宽度
        this.img.height * devicePixelRatio, // 源图像的高度
        this.tx, // 目标画布上源图像左上角的 x 坐标
        this.ty, // 目标画布上源图像左上角的 y 坐标
        this.twidth * devicePixelRatio, // 画布上绘制图像的宽度
        this.theight * devicePixelRatio // 画布上绘制图像的高度
      )
    }else{
    
       ctx.drawImage(
        this.img,
        this.x, // 源图像的x坐标
        this.y, // 源图像的y坐标
        this.img.width, // 源图像的宽度
        this.img.height, // 源图像的高度
        (this.tx-databus.hero.tx)*16*devicePixelRatio, // 目标画布上源图像左上角的 x 坐标
        (this.ty-databus.hero.ty)*16*devicePixelRatio, // 目标画布上源图像左上角的 y 坐标
        this.twidth*16 * devicePixelRatio, // 画布上绘制图像的宽度
        this.theight*16 * devicePixelRatio // 画布上绘制图像的高度
      )
      // console.log('npc',this.twidth*16 * devicePixelRatio,this.theight*16 * devicePixelRatio)
    }
  }
  /**
   * 更新精灵的方法
   * @param {String} type: 精灵的类型
   * @param {int} loop: 是否循环,0循环，否则为执行次数
   */
  update(frame, type, loop) {
    // frame = "5.bmp",0.05;
    
    const duration = this[type][this.frameIndex % this[type].length].duration*200
    // console.log(frame/duration)
    if (frame % duration === 0) {
       loop = this.normal.length
      if (this.frameLoop<loop||loop==0) {
        this.img = new Image()
        this.img.src = this.dir+this[type][this.frameIndex % this[type].length].frame.split('=')[1].trim()
        this.frameIndex = (this.frameIndex + 1) % this[type].length;
        this.frameLoop+=1
      } 
      if(this.spriteName=='startMovie'&&this.frameLoop==loop){
        databus.mode='start'
      }
    }
  }

  /**
   * 简单的碰撞检测定义：
   * 另一个精灵的中心点处于本精灵所在的矩形内即可
   * @param{Sprite} sp: Sptite的实例
   */
  isCollideWith(sp) {
    const spX = sp.x + sp.width / 2
    const spY = sp.y + sp.height / 2

    if (!this.visible || !sp.visible) return false

    return !!(spX >= this.x
              && spX <= this.x + this.width
              && spY >= this.y
              && spY <= this.y + this.height)
  }
}
